package test.java.question;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

/**
 *  * @Description 实现一个容器，提供两个方法，add，count 写两个线程，
 *  * 线程1添加10个元素到容器中，线程2实现监控元素的个数，
 *  * 当个数到5个时，线程2给出提示并结束。
 */
public class AddAndCount {
    public static void main(String[] args) {
        AddAndCount adc = new AddAndCount();
        new Thread(adc::add,"A").start();
        new Thread(adc::count,"B").start();
    }
    ArrayList<String> list = new ArrayList<>();
    CountDownLatch cdl = new CountDownLatch(1);
    void add(){
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            String item = String.format("%s - %d","item",i);
            list.add(item);
            System.out.println(Thread.currentThread().getName() + ":" +item);
            if (i == 4){
                cdl.countDown();
            }
        }
    }

    void count(){
        try {
            cdl.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("程序结束........");
        System.exit(0);

    }
}
